package 网络编程;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Inet6Address;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class ServiceSocketTest {

    public static void main(String[] args) {

        try {
            // 创建一个ServerSocket, 用于监听客户端Socket的连接请求
            // 端口，请求连接队列最大长度，服务端IP
            ServerSocket serverSocket = new ServerSocket(6666, 3, Inet6Address.getLocalHost());
            //用循环不断接收来自客户端的请求
            while (true) {
                // 请求连接队列中获取一个 socket 并建立连接
                Socket socket = serverSocket.accept();

                // 将流中数据输入到程序中
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println("server receipt: " + bufferedReader.readLine());

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bufferedWriter.write("my is server");
                // 注意: 这里需要换行，刷新
                bufferedWriter.newLine();
                bufferedWriter.flush();

                // 关闭流，关闭socket
                bufferedReader.close();
                bufferedWriter.close();
                socket.close();
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }

}
